package com.ABdolphin.forum.controller;

import com.ABdolphin.forum.common.AppConfig;
import com.ABdolphin.forum.common.AppResult;
import com.ABdolphin.forum.common.ResultCode;
import com.ABdolphin.forum.exception.ApplicationException;
import com.ABdolphin.forum.model.User;
import com.ABdolphin.forum.services.IUserService;
import com.ABdolphin.forum.utils.MD5Util;
import com.ABdolphin.forum.utils.StringUtil;
import com.ABdolphin.forum.utils.UUIDUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;

import java.net.http.HttpRequest;

@RequestMapping("/user")
@RestController
@Slf4j
@Tag(name = "用户接口")
public class UserController {
    @Resource
    private IUserService userService;
    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public AppResult register(@Parameter(name = "userName" ,description = "姓名") @RequestParam("userName") @NotNull String userName,
                              @Parameter(name = "nickname",description = "昵称") @RequestParam("nickname") @NotNull String nickname,
                              @Parameter(name = "password",description = "密码") @RequestParam("password") @NotNull String password,
                              @Parameter(name = "passwordRepeat",description = "确认密码") @RequestParam("passwordRepeat") @NotNull String passwordRepeat){
        if (!password.equals(passwordRepeat)){
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        User user=new User();
        user.setUserName(userName);
        user.setNickname(nickname);
        String salt = UUIDUtil.UUID_32();
        String encryptPassword = MD5Util.md5Salt(password, salt);
        user.setPassword(encryptPassword);
        user.setSalt(salt);
        userService.createNormalUser(user);
        return AppResult.success();
    }
    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public AppResult login(HttpServletRequest request,
                           @Parameter(name = "userName",description = "姓名" ) @RequestParam("userName") @NotNull String userName,
                           @Parameter(name = "password",description = "密码" ) @RequestParam("password") @NotNull String password){
        User user = userService.login(userName, password);
        if(user==null){
            log.warn(ResultCode.FAILED_LOGIN.toString()+",userName"+userName);
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION,user);
        return AppResult.success();
    }
    @GetMapping("/info")
    @Operation(summary = "获得用户信息")
    public AppResult getUserInfo(HttpServletRequest request,
                                 @Parameter(name = "id",description = "用户id") @RequestParam(value = "id",required = false) Long id){
        User user=null;
        if(id==null) {
            //1如果id为空,就要从session中获得信息
            //如果没有session不主动创建session
            HttpSession session = request.getSession(false);
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        }else{
            //2,如果不为空,就要从到中访问数据库获得信息
            user=userService.selectById(id);
        }
        //判断对象是否为空
        if(user==null){
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return AppResult.success(user);
    }
    @GetMapping("/logout")
    @Operation(summary = "退出登录")
    public AppResult logout(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        if (session!=null){
            //表示用户在登录状态
            log.info("退出成功");
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }
    @PostMapping("/modifyInfo")
    @Operation(summary = "修改个人信息")
    public AppResult modifyInfo(HttpServletRequest request,
                                @Parameter(name = "userName",description = "用户名")@RequestParam(value = "userName",required = false) String userName,
                                @Parameter(name = "nickname",description = "昵称")@RequestParam(value = "nickname",required = false)String nickname,
                                @Parameter(name = "gender",description = "性别")@RequestParam(value = "gender",required = false)Byte gender,
                                @Parameter(name = "email",description = "邮箱")@RequestParam(value = "email",required = false)String email,
                                @Parameter(name = "phoneNum",description = "电话号码")@RequestParam(value = "phoneNum",required = false)String phoneNum,
                                @Parameter(name = "remark",description = "个人简介")@RequestParam(value = "remark",required = false)String remark){
        if (StringUtil.isEmpty(userName)&&StringUtil.isEmpty(nickname)
                &&StringUtil.isEmpty(email)&&StringUtil.isEmpty(phoneNum)
                &&StringUtil.isEmpty(remark)&&gender==null){
            return AppResult.failed("请输入要修改的内容");
        }
        HttpSession session = request.getSession(false);
        User user=(User)session.getAttribute(AppConfig.USER_SESSION);
        User updateUser=new User();
        updateUser.setId(user.getId());
        updateUser.setUserName(userName);
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);
        userService.modifyInfo(updateUser);
        user=userService.selectById(user.getId());
        session.setAttribute(AppConfig.USER_SESSION,user);
        return AppResult.success(user);
    }
    @Operation(summary = "修改密码")
    @PostMapping("/modifyPwd")
    public  AppResult modifyPassword(HttpServletRequest request,
                                     @Parameter(name = "newPassword",description = "新密码")@RequestParam("newPassword")@NotBlank String newPassword,
                                     @Parameter(name = "oldPassword",description = "旧密码")@RequestParam("oldPassword")@NotBlank String oldPassword,
                                     @Parameter(name = "passwordRepeat",description = "确认密码")@RequestParam("passwordRepeat")@NotBlank String passwordRepeat){
        if (!newPassword.equals(passwordRepeat)){
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        HttpSession session = request.getSession(false);
        User user=(User) session.getAttribute(AppConfig.USER_SESSION);
        userService.modifyPassword(user.getId(),newPassword,oldPassword);
        if (session!=null){
            session.invalidate();
        }
        return AppResult.success();
    }

}




















